package com.zhang.resource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * @Package: com.zhang.resource.config
 * @ClassName: MyResourceServerConfig
 * @Author: Think
 * @CreateTime: 2021/8/7 14:32
 * @Description:
 */
@Configuration
@EnableResourceServer
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerTokenServices tokenService;

    /**
     * 系统启动时就加载——资源配置
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 本资源服务的ID，用于在授权服务器那里验证是否存在这个ID的资源服务
        resources.resourceId("user")
                // 加载token规则
                .tokenServices(tokenService)
                // 禁用session
                .stateless(true);
    }

    /**
     * 系统启动时就加载——对请求进行鉴权的配置
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 任何请求都必须具有all这个域的授权
                .antMatchers("/**").access("#oauth2.hasScope('all')")
                .and()
                .csrf().disable()
                // 禁用session，因为我们使用的是token，session没有用途
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    /**
     * 定义校验token的规则
     * @return
     */
    @Bean
    public ResourceServerTokenServices tokenService(){
        // 当授权服务器和资源服务器不是同一台机器时需要使用RemoteTokenServices
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        // 指定授权服务器校验token的端点
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
        // 资源服务器自己独有的身份信息
        remoteTokenServices.setClientId("iSchool");
        remoteTokenServices.setClientSecret("mysecret");
        return remoteTokenServices;
    }
}
